﻿using System;
using System.IO;
using System.Web.Mvc;

namespace DBFile.Core.Web.Mvc
{
    public class DBFileResult : FileResult
    {
        public DBFileResult(string fileName, string contentType)
            : base(contentType)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("Filename is required.", "fileName");
            }
            this.FileName = fileName;
            this.FileDownloadName = fileName;
        }

        public string FileName { get; private set; }
        
        protected override void WriteFile(System.Web.HttpResponseBase response)
        {
            using (Stream file = DBFile.Open(FileName))
            {
                byte[] buffer = new byte[2048];
                while (true)
                {
                    int count = file.Read(buffer, 0, 2048);
                    if (count == 0)
                    {
                        return;
                    }
                    response.OutputStream.Write(buffer, 0, count);
                }
            }
        }
    }
}
